using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using Commerce.Common;
using Commerce.Messaging;

/// <summary>
/// Summary description for MessagingController
/// </summary>
public static class MessagingController
{
        /// <summary>
    /// This method can be used for all kinds of fun things - like dropping an EDI x12 document, or an
    /// XML message for BizTalk. For instance, you can serialize down an order simply by using
    /// order.ToXML(), put that string into a document (it's well-formatted XML already), and 
    /// drop it on an FTP server.
    /// </summary>
    /// <param name="absoluteFilePath">The path to the file to send</param>
    /// <param name="ftpServerUrl">should be something like ftp://servername.com/directory</param>
    /// <param name="userName">FTP username</param>
    /// <param name="password">FTP password</param>
    public static void SendFTP(string absoluteFilePath, string ftpServerUrl, string userName, string password)
    {

        FTPClient.PutFile(absoluteFilePath,
            ftpServerUrl, userName, password);
    }

    
    public enum Message : int
    {
        OrderReceivedEmail = 1,
        MailerToCustomer = 2,
        ShippingNotification = 3,
        OrderCancellations = 4,
        OrderRefunded = 5,
        NewAccount = 8,
        ChangedPassword = 9
    }

    private static string ReplacePlaceholders(string email, Order order, MessagingMailer mailer)
    {
        string sMessage = email;

        if (!mailer.IsHTML)
        {
            sMessage = sMessage.Replace("#NAME#", order.FirstName + " " + order.LastName);

            if (order.ShippingAddress != null)
            {
                sMessage = sMessage.Replace("#SHIPPINGINFO#", order.ShippingAddress.ToString());
            }
            else
            {
                sMessage = sMessage.Replace("#SHIPPINGINFO#", "");
            }

            if (order.BillingAddress != null)
            {
                sMessage = sMessage.Replace("#BILLINGINFO#", order.BillingAddress.ToString());
            }
            else
            {
                sMessage = sMessage.Replace("#BILLINGINFO#", "");
            }

            sMessage = sMessage.Replace("#ORDERITEMS#", order.ItemsToString(false));

            sMessage = sMessage.Replace("#ORDERNUMBER#", order.OrderNumber);
            
            sMessage = sMessage.Replace("#PONUMBER#", order.PoNumber);

            sMessage = sMessage.Replace("#TOTAL#", order.OrderTotal.ToString("C"));

            sMessage = sMessage.Replace("#TRACKINGNUMBER#", order.ShippingTrackingNumber);                    

            sMessage = sMessage.Replace("#STOREEMAIL#", mailer.FromEmail);

            // tagline
            sMessage = sMessage.Replace("#TAGLINE#", ConfigurationManager.AppSettings["tagLine"]);

            // items
            sMessage = sMessage.Replace("#LINK#", Utility.GetSiteRoot());

            sMessage = sMessage.Replace("#ORDERLINK#", String.Format("{0}/umbraco/commerce/editOrder.aspx?o={1}", Utility.GetSiteRoot(), order.OrderID));
        }
        else
        {
            //run some tag replacements. First with the name
            sMessage = sMessage.Replace("#NAME#", order.FirstName + " " + order.LastName);

            if (order.ShippingAddress != null)
            {
                sMessage = sMessage.Replace("#SHIPPINGINFO#", order.ShippingAddress.ToHtmlString());
            }
            else
            {
                sMessage = sMessage.Replace("#SHIPPINGINFO#", "");
            }

            if (order.BillingAddress != null)
            {
                sMessage = sMessage.Replace("#BILLINGINFO#", order.BillingAddress.ToHtmlString());
            }
            else
            {
                sMessage = sMessage.Replace("#BILLINGINFO#", "");
            }

            sMessage = sMessage.Replace("#ORDERITEMS#", order.ItemsToString(true));

            sMessage = sMessage.Replace("#ORDERNUMBER#", order.OrderNumber);

            sMessage = sMessage.Replace("#TOTAL#", order.OrderTotal.ToString("C"));

            sMessage = sMessage.Replace("#TRACKINGNUMBER#", order.ShippingTrackingNumber);                    

            //admin email
            sMessage = sMessage.Replace("#STOREEMAIL#", String.Format("<a href='mailto:{0}'>{0}</a>", mailer.FromEmail));

            //tagline
            sMessage = sMessage.Replace("#TAGLINE#", ConfigurationManager.AppSettings["tagLine"]);

            //link
            sMessage = sMessage.Replace("#LINK#", String.Format("<a href='{0}'>{0}</a>", Utility.GetSiteRoot()));

            sMessage = sMessage.Replace("#ORDERLINK#", String.Format("<a href='{0}/umbraco/commerce/editOrder.aspx?o={1}'>{2}</a>", Utility.GetSiteRoot(), order.OrderID, order.OrderNumber));
        }

        return sMessage;
    }

    /// <summary>
    /// This method will send a message to the shop owner, notifying them of a new order
    /// </summary>
    /// <param name="order">The order itself</param>
    /// <returns></returns>
    public static bool SendMerchantOrderNotice(Order order)
    {
        bool bOut = false;

        try
        {
            //load up the template
            //string template = Utility.GetFileText("MailerTemplates/MailerToMerchant.txt");

            //get the mailer from the DB
            int mailerID = Convert.ToInt16(Message.OrderReceivedEmail);
            //Email mailer = new Email(mailerID);
            MessagingMailer mailer = new MessagingMailer(mailerID);
            string template = mailer.MessageBody;

            //we're overriding the DB templates
            //use the text template
            //it's formatted nicely
            if (template.Length > 0)
            {
                // run some tag replacements. First with the name
                string sMessage = ReplacePlaceholders(template, order, mailer);
               
                //setup the mailer
                mailer.MessageBody = sMessage;
                // PVS 8/16/2007 - not sure why this was set to send to the order email
                //                  changed to leave as set in DB
                //mailer.ToList = order.Email;

                //send it off!
                bOut = Email.SendEmail(mailer);

            }
        }
        catch (Exception e)
        {
            bOut = false;
        }

        return bOut;

    }

    /// <summary>
    /// This is an overriden method of the Mailer class. The default message in the DB is going
    /// to be overwritten with a nicely formatted HTML message stored in the EmailTemplates
    /// Directory. Feel free to change as needed.
    /// </summary>
    /// <param name="order">The order to send out the mailer for.</param>
    /// <returns></returns>
    public static bool SendOrderReceivedEmail(Order order)
    {
        bool bOut = false;

        try
        {
            //get the mailer from the DB
            int mailerID = Convert.ToInt16(Message.MailerToCustomer);
            //Email mailer = new Email(mailerID);
            MessagingMailer mailer = new MessagingMailer(mailerID);

            //load up the template
            //there is a text template too...
            //string template = Utility.GetFileText("MailerTemplates/OrderConfirm.txt");
            //mailer.IsHTML = false;
            string template = mailer.MessageBody;


            if (template.Length > 0)
            {
                string sMessage = ReplacePlaceholders(template, order, mailer);

                //setup the mailer
                mailer.MessageBody = sMessage;
                mailer.ToList = order.Email;

                //send it off!
                bOut = Email.SendEmail(mailer);

            }

        }
        catch (Exception e)
        {
            bOut = false;
        }


        return bOut;
    }


    /// <summary>
    /// This is an overriden method of the Mailer class. The default message in the DB is going
    /// to be overwritten with a nicely formatted HTML message stored in the EmailTemplates
    /// Directory. Feel free to change as needed.
    /// </summary>
    /// <param name="order">The order to send out the mailer for.</param>
    /// <returns></returns>
    public static bool SendOrderShippedEmail(Order order)
    {
        bool bOut = false;

        try
        {
            //get the mailer from the DB
            int mailerID = Convert.ToInt16(Message.ShippingNotification);
            //Email mailer = new Email(mailerID);
            MessagingMailer mailer = new MessagingMailer(mailerID);

            //load up the template
            //there is a text template too...
            //string template = Utility.GetFileText("MailerTemplates/OrderConfirm.txt");
            //mailer.IsHTML = false;
            string template = mailer.MessageBody;


            if (template.Length > 0)
            {
                //string sMessage = template;
                string sMessage = ReplacePlaceholders(template, order, mailer);

                //setup the mailer
                mailer.MessageBody = sMessage;
                mailer.ToList = order.Email;

                //send it off!
                bOut = Email.SendEmail(mailer);

            }

        }
        catch (Exception e)
        {
            bOut = false;
        }


        return bOut;
    }



    /// <summary>
    /// This is an overriden method of the Mailer class. The default message in the DB is going
    /// to be overwritten with a nicely formatted HTML message stored in the EmailTemplates
    /// Directory. Feel free to change as needed.
    /// </summary>
    /// <param name="order">The order to send out the mailer for.</param>
    /// <returns></returns>
    public static bool SendOrderCancelledEmail(Order order)
    {
        bool bOut = false;

        try
        {
            //get the mailer from the DB
            int mailerID = Convert.ToInt16(Message.OrderCancellations);
            //Email mailer = new Email(mailerID);
            MessagingMailer mailer = new MessagingMailer(mailerID);

            //load up the template
            //there is a text template too...
            //string template = Utility.GetFileText("MailerTemplates/OrderConfirm.txt");
            //mailer.IsHTML = false;
            string template = mailer.MessageBody;


            if (template.Length > 0)
            {
                string sMessage = ReplacePlaceholders(template, order, mailer);

                //setup the mailer
                mailer.MessageBody = sMessage;
                mailer.ToList = order.Email;

                //send it off!
                bOut = Email.SendEmail(mailer);

            }

        }
        catch (Exception e)
        {
            bOut = false;
        }


        return bOut;
    }


    /// <summary>
    /// This is an overriden method of the Mailer class. The default message in the DB is going
    /// to be overwritten with a nicely formatted HTML message stored in the EmailTemplates
    /// Directory. Feel free to change as needed.
    /// </summary>
    /// <param name="order">The order to send out the mailer for.</param>
    /// <returns></returns>
    public static bool SendOrderRefundedEmail(Order order)
    {
        bool bOut = false;

        try
        {
            //get the mailer from the DB
            int mailerID = Convert.ToInt16(Message.OrderRefunded);
            //Email mailer = new Email(mailerID);
            MessagingMailer mailer = new MessagingMailer(mailerID);

            //load up the template
            //there is a text template too...
            //string template = Utility.GetFileText("MailerTemplates/OrderConfirm.txt");
            //mailer.IsHTML = false;
            string template = mailer.MessageBody;


            if (template.Length > 0)
            {
                string sMessage = ReplacePlaceholders(template, order, mailer);

                //setup the mailer
                mailer.MessageBody = sMessage;
                mailer.ToList = order.Email;

                //send it off!
                bOut = Email.SendEmail(mailer);

            }

        }
        catch (Exception e)
        {
            bOut = false;
        }


        return bOut;
    }


    /// <summary>
    /// This is an overriden method of the Mailer class. The default message in the DB is going
    /// to be overwritten with a nicely formatted HTML message stored in the EmailTemplates
    /// Directory. Feel free to change as needed.
    /// </summary>
    /// <returns></returns>
    public static bool SendNewAccountEmail(string name, string email)
    {
        bool bOut = false;

        try
        {
            //get the mailer from the DB
            int mailerID = Convert.ToInt16(Message.NewAccount);
            //Email mailer = new Email(mailerID);
            MessagingMailer mailer = new MessagingMailer(mailerID);

            //load up the template
            //there is a text template too...
            //string template = Utility.GetFileText("MailerTemplates/OrderConfirm.txt");
            //mailer.IsHTML = false;
            string template = mailer.MessageBody;


            if (template.Length > 0)
            {
                string sMessage = template;

                if (!mailer.IsHTML)
                {
                    sMessage = sMessage.Replace("#NAME#", name);

                    sMessage = sMessage.Replace("#TAGLINE#", ConfigurationManager.AppSettings["tagLine"]);

                    //link
                    sMessage = sMessage.Replace("#LINK#", String.Format("{0}", Utility.GetSiteRoot()));

                }
                else
                {
                    //run some tag replacements. First with the name
                    sMessage = sMessage.Replace("#NAME#", name);

                    sMessage = sMessage.Replace("#TAGLINE#", ConfigurationManager.AppSettings["tagLine"]);

                    //link
                    sMessage = sMessage.Replace("#LINK#", String.Format("<a href='{0}'>{0}</a>", Utility.GetSiteRoot()));

                }

                //setup the mailer
                mailer.MessageBody = sMessage;
                mailer.ToList = email;

                //send it off!
                bOut = Email.SendEmail(mailer);

            }

        }
        catch (Exception e)
        {
            bOut = false;
        }


        return bOut;
    }

    /// <summary>
    /// This is an overriden method of the Mailer class. The default message in the DB is going
    /// to be overwritten with a nicely formatted HTML message stored in the EmailTemplates
    /// Directory. Feel free to change as needed.
    /// </summary>
    /// <returns></returns>
    public static bool SendChangedPasswordEmail(string name, string email)
    {
        bool bOut = false;

        try
        {
            //get the mailer from the DB
            int mailerID = Convert.ToInt16(Message.ChangedPassword);
            //Email mailer = new Email(mailerID);
            MessagingMailer mailer = new MessagingMailer(mailerID);

            //load up the template
            //there is a text template too...
            //string template = Utility.GetFileText("MailerTemplates/OrderConfirm.txt");
            //mailer.IsHTML = false;
            string template = mailer.MessageBody;


            if (template.Length > 0)
            {
                string sMessage = template;

                if (!mailer.IsHTML)
                {
                    sMessage = sMessage.Replace("#NAME#", name);

                    sMessage = sMessage.Replace("#TAGLINE#", ConfigurationManager.AppSettings["tagLine"]);

                    //link
                    sMessage = sMessage.Replace("#LINK#", String.Format("{0}", Utility.GetSiteRoot()));

                }
                else
                {
                    //run some tag replacements. First with the name
                    sMessage = sMessage.Replace("#NAME#", name);

                    sMessage = sMessage.Replace("#TAGLINE#", ConfigurationManager.AppSettings["tagLine"]);

                    //link
                    sMessage = sMessage.Replace("#LINK#", String.Format("<a href='{0}'>{0}</a>", Utility.GetSiteRoot()));

                }

                //setup the mailer
                mailer.MessageBody = sMessage;
                mailer.ToList = email;

                //send it off!
                bOut = Email.SendEmail(mailer);

            }

        }
        catch (Exception e)
        {
            bOut = false;
        }


        return bOut;
    }


    /// <summary>
    /// This is an overriden method of the Mailer class. The default message in the DB is going
    /// to be overwritten with a nicely formatted HTML message stored in the EmailTemplates
    /// Directory. Feel free to change as needed.
    /// </summary>
    /// <returns></returns>
    public static bool SendTestEmail(string email, int mailerID, out string errorMessage)
    {
        bool bOut = false;
        errorMessage = "";

        try
        {
            MessagingMailer mailer = new MessagingMailer(mailerID);

            //load up the template
            //there is a text template too...
            //string template = Utility.GetFileText("MailerTemplates/OrderConfirm.txt");
            //mailer.IsHTML = false;
            string template = mailer.MessageBody;


            if (template.Length > 0)
            {
                string sMessage = template;

                //setup the mailer
                mailer.MessageBody = sMessage;
                mailer.ToList = email;

                //send it off!
                bOut = Email.SendEmail(mailer);
            }

        }
        catch (Exception e)
        {
            bOut = false;
            string inner = "";
            if (e.InnerException != null)
            {
                Exception iex = e.InnerException;
                inner = String.Format("<h2>A problem occurred:</h2><p>{0}</p><p>{1}</p>", iex.Message, iex.StackTrace);
            }
            errorMessage = String.Format("<h2>A problem occurred:</h2><p>{0}</p><p>{1}</p><p>{2}</p>", e.Message, e.StackTrace, inner);
        }


        return bOut;
    }
}
